// pages/login.js
"use client";
import { useRouter } from "next/navigation";
import React from "react";
import { Form, Input, Button, Checkbox, message } from "antd";

import styles from "./login.module.css";

const Login = () => {
  const router = useRouter();
  // const [messageApi, contextHolder] = message.useMessage();

  const onFinish = async (values) => {
    console.log(" JSON.stringify(values)", JSON.stringify(values));
    let res = await fetch("/api/admin/login", {
      method: "POST",
      body: JSON.stringify(values),
      headers: {
        "Content-Type": "application/json",
      },
    });
    res = await res.json();
    console.log("res1111", res);
    if (res.success) {
      // 使用 setTimeout 延迟调用 success
      message.success("登录成功");
      router.push("/admin/users");
    } else {
      // 使用 setTimeout 延迟调用 error
      message.error(res.errorMessage);
    }
  };

  const onFinishFailed = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-900">
      <div className={styles.container}>
        <Form
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
        >
          <Form.Item
            label="账号"
            name="username"
            rules={[{ required: true, message: "Please input your username!" }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="密码"
            name="password"
            rules={[{ required: true, message: "Please input your password!" }]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item
            name="remember"
            valuePropName="checked"
            wrapperCol={{ offset: 8, span: 16 }}
          >
            <Checkbox> 记住密码</Checkbox>
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button type="primary" htmlType="submit">
              登陆
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default Login;
